#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import requests
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC


def browser(edge_options=None):
    """ open browser edge """
    if edge_options is None:
        # 设置Edge选项
        edge_options = webdriver.EdgeOptions()
        edge_options.add_experimental_option("detach", True)  # 防止浏览器自动关闭
        edge_options.add_experimental_option(
            "excludeSwitches", ["enable-logging"])  # 禁用日志输出
    # 启动Edge浏览器
    return webdriver.Edge(options=edge_options)


def get_elements(url, driver=None, xpath='//*'):
    """ 加载 url """
    if driver is None:
        driver = browser()
    # 打开网页
    driver.get(url)
    # 等待页面加载
    locator = (By.XPATH, xpath)
    condition = EC.presence_of_all_elements_located(locator)
    return WebDriverWait(driver, 3).until(condition)


def main(url="https://mail.bit.edu.cn", xpath='//*'):
    """ 运行脚本 """
    driver = browser()
    elements = get_elements(url, driver, xpath)
    for element in elements:
        print(f'element = {element.__class__}')
        print(f'tag_name = {element.tag_name}')
        print(f'location = {element.location}')
        print(f'text = {element.text}')
    driver.close()


if __name__ == '__main__':
    print(f'Running {sys.argv[0]}')
    main(xpath='//@tag_name')
    print(f'Exit {sys.argv[0]}')
